import AMapLoader from '@amap/amap-jsapi-loader';
import { useCallback, useEffect, useRef, useState } from 'react';


export type CallBackPramse = { AMap: typeof AMap, map: AMap.Map, event: AMap.MapsEvent }

type MapEventItem = {
  type: AMap.EventType,
  callBack: (e: CallBackPramse) => void
}

interface Props {
  id: string,
  mapOption: AMap.MapOptions,
  mapEvents?: MapEventItem[]
  // mapClick?: (e: { AMap: typeof AMap, map: AMap.Map, event: AMap.MapsEvent }) => void
}

const useGetMap = ({ id, mapOption, mapEvents }: Props) => {

  const map = useRef<AMap.Map | null>(null)

  // const [map, setMap] = useState<AMap.Map | null>()
  const [loading, setLoading] = useState<boolean>(true)
  const [loca, setLoca] = useState<typeof Loca | null>(null)
  const [_AMap, setAMap] = useState<typeof AMap | null>(null)

  const init = useCallback(() => {

    AMapLoader.load({
      key: "fa8bb66eb1640af90429418af84bc0a7",              // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0",       // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: [],
      Loca: {                // 是否加载 Loca， 缺省不加载
        version: '2.0.0'  // Loca 版本，缺省 1.3.2
      },
    }).then((AMap) => {
      const map_init = new AMap.Map(id, mapOption);

      if (mapEvents && mapEvents.length) {
        mapEvents.forEach((item) => {
          map_init.on(item.type, (_event: AMap.MapsEvent) => {
            console.log(`触发地图${item.type}事件`);
            item.callBack({ AMap, map: map_init, event: _event })
          });
        })
      }

      map_init.on('complete', () => {
        map.current = map_init
        const timer = setTimeout(()=>{
          setLoading(false)
          clearTimeout(timer)
        },500)
        setLoca(Loca)
        setAMap(AMap)
        console.log('触发地图资源加载完成事件');
      });
    }).catch(e => {
      console.log(e);
    })


  }, [id])


  const destroyMap = useCallback(() => {
    console.log(map.current, '准备销毁地图');

    if (!map.current) return
    map.current.destroy()
    map.current = null
    console.log('地图销毁', map.current);
  }, [map])



  useEffect(() => {

    init()
  }, [init])


  return {
    map: map.current,
    loading,
    locaLib: loca,
    AMap: _AMap,
    destroyMap
  }
}

export default useGetMap